#include "etc/os-release.h"

bool os_release_of_buffer(char *buf, OS_Release *os) {
    if(isNull(buf)) return false;
    
    GSList *list = split(buf, '=');
    for (int i = 0; i < sizeof(os_release_properties)/sizeof(os_release_properties[0]); i++) {
        if (LineStartWith(buf, (char*)os_release_properties[i])) {
            switch (i) {
            case 0: strcpy(os->name, (char*)g_slist_nth(list, 1)->data); break;
            case 1: strcpy(os->version, (char*)g_slist_nth(list, 1)->data); break;
            case 2: strcpy(os->version_id, (char*)g_slist_nth(list, 1)->data); break;
            case 3: strcpy(os->version_date, (char*)g_slist_nth(list, 1)->data); break;

            case 4: strcpy(os->home_url, (char*)g_slist_nth(list, 1)->data); break;
            case 5: strcpy(os->support_url, (char*)g_slist_nth(list, 1)->data); break;
            case 6: strcpy(os->bug_report_url, (char*)g_slist_nth(list, 1)->data); break;
            }
        }
    }
    GS_FREE_ALL_CLEAN(list)

    return true;
}

bool etc_os_release_of_buffer(char *buf, OS_Release *os) {
    if(isNull(buf)) return false;

    char *buffer = LineTrim(buf);

    GSList *list = split(buffer, '\n');
    for (GSList *iter = list; iter; iter = iter->next) {
        os_release_of_buffer(iter->data, os);
    }
    
    GS_FREE_ALL_CLEAN(list);

    S_FREE(buffer);

    return true;
}

bool etc_os_release_of_path(char *path, OS_Release *os) {
    if (!FileExists(path)) return false;

    bool eof = false;
    FILE *fp = fopen(path, "r");

    while (!eof)
    {
        char buffer[100] = {0};
        eof = freadline(fp, buffer);
        if (eof) continue;

        os_release_of_buffer(buffer, os);
    }

    fclose(fp);

    return true;
}

bool initOsRelease(OS_Release *os) {
    if (!FileExists(LINUX_OS_RELEASE_CONFIG)) return false;

    char buffer[10000] = {0};
    if (FileReadToBuffer(LINUX_OS_RELEASE_CONFIG, buffer, sizeof(buffer))) {
        return etc_os_release_of_buffer(buffer, os);
    }
    // return etc_os_release_of_path(LINUX_OS_RELEASE_CONFIG, os);
    return false;
}
